<template>
  <el-button
    v-bind="$attrs"
    :loading="loading"
    @click.prevent="onClick"
  >
    <slot />
  </el-button>
</template>

<script>
export default {
  name: "t-button",
  props: {
    //点击过渡状态
    transition: {
      type: String,
      default: "none", //debounce : 事件节流  loading : loading // 不设置过渡  none
    },
    /**
     * loading 实例
     * <t-button  transition="loading" @click="onClick">onClick</t-button>
     *  onClick(done){
          setTimeout(() => {
            done()
          }, 2000);
        },
     */
    /**
     * debounce 实例
     * <t-button  transition="debounce" :throatTime="1000" @click="onClick">onClick</t-button>
     *  onClick(done){
          console.log(1秒内只执行一次)
        },
     */

    throatTime: {
      //节流时间
      type: Number,
      default: 2000,
    },
  },
  data() {
    return {
      loading: false,
      timer: null,
      disabled: false,
    };
  },
  methods: {
    onClick() {
      if (this.transition == "debounce") {
        this.throat();
      } else if (this.transition == "loading") {
        this.handleLoadingClick();
      } else {
        this.emit();
      }
    },
    throat() {
      if (!this.timer) {
        this.emit();
        this.timer = setTimeout(() => {
          this.timer = null;
          this.$attrs.disabled = false;
        }, this.throatTime); //默认1s的，节流
      } else {
        // this.$message.warning("点击太过频繁，休息一下再试！");
       this.$attrs.disabled = true;
      }
    },
    emit() {
      this.$emit("click");
    },
    handleLoadingClick() {
      this.loading = true;
      this.$emit("click", () => {
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.t-button {
  display: inline-block;
}
</style>